package Com.Ring.TradingMobile;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import Com.Ring.TradingMobile.Lib.Common;
import Com.Ring.TradingMobile.Lib.CompanyListAdapter;
import Com.Ring.TradingMobile.Object.CompanyInfo;
import Com.Ring.TradingMobile.Object.StockInfo;
import Com.Ring.TradingMobile.SQLite.DBManager;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Contacts;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.SimpleAdapter;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TableRow.LayoutParams;
import android.widget.TextView;

public class HistoryActivity extends Activity {

	final static String TAG = "History";
	DBManager dbData;
	private TextView txtFromDate;
	private TextView txtToDate;
	private TextView txtStock;

	private int FromYear;
	private int FromMonth;
	private int FromDay;
	private int ToYear;
	private int ToMonth;
	private int ToDay;

	static final int FROM_DATE_DIALOG_ID = 0;
	static final int TO_DATE_DIALOG_ID = 1;
	static final int DIALOG_LOADING = 3;

	private Button btnXem;
	private Button btnFromDate;
	private Button btnToDate;

	private Button btnBack;

	private LinearLayout linearHeader;
	private LinearLayout linearContent;

	private AutoCompleteTextView AutoCompleteStock;

	private String Code = "";

	public boolean IsUpdateCompany;
	public boolean IsUpdateStockInfoRunning;
	public boolean IsRunningUpdate;
	
	private CompanyInfoAsyncTask companyInfoAsyncTask;
	private StockInfoAsyncTask stockInfoAsyncTask;

	private int[] StrHeaderId = new int[]{R.string.strDate, R.string.strRef,
			R.string.strCeiling, R.string.strFloor, R.string.strLast,
			R.string.strChange, R.string.strVol, R.string.strBestBuyPrice,
			R.string.strBestBuyVol, R.string.strBestSellPrice,
			R.string.strBestSellVol, R.string.strTotalVol};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.history);
		FindViewId();
		SetOnListener();
		// InitThread();
		final Calendar c = Calendar.getInstance();
		ToYear = FromYear = c.get(Calendar.YEAR);
		ToMonth = FromMonth = c.get(Calendar.MONTH);
		ToDay = FromDay = c.get(Calendar.DAY_OF_MONTH);
		updateDisplayFrom();
		updateDisplayTo();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	@Override
	protected void onStart() {
		final Calendar c = Calendar.getInstance();
		Log.d(TAG,"Begin Load CompanyInfo: "+c.getTime().toLocaleString());
		//LoadCompanyInfo();
		 dbData = new DBManager(HistoryActivity.this);
		CompanyListAdapter apdater = new CompanyListAdapter(this, TAG, this, R.layout.two_line_list_item, null);
		AutoCompleteStock.setAdapter(apdater);
		super.onStart();
		
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		dbData.close();
		CancelLoadCompanyInfo();
		CancelLoadStockInfo();
	}

	private void FindViewId() {
		txtFromDate = (TextView) findViewById(R.id.lblFromDate);
		txtToDate = (TextView) findViewById(R.id.lblToDate);
		txtStock = (TextView) findViewById(R.id.lblStock);
		btnFromDate = (Button) findViewById(R.id.btnFromDate);
		btnToDate = (Button) findViewById(R.id.btnToDate);
		btnXem = (Button) findViewById(R.id.btnXem);

		btnBack = (Button) findViewById(R.id.btnBack);

		linearHeader = (LinearLayout) findViewById(R.id.linearHeader);
		linearContent = (LinearLayout) findViewById(R.id.linearContent);
		AutoCompleteStock = (AutoCompleteTextView) findViewById(R.id.autoCompleteMarket);

		TableLayout tableHeader = new TableLayout(this);
		TableRow[] rowsHeader = new TableRow[StrHeaderId.length];
		TextView[] txtHeader = new TextView[StrHeaderId.length];
		for (int i = 0; i < txtHeader.length; i++) {
			rowsHeader[i] = new TableRow(this);
			txtHeader[i] = new TextView(this);
			txtHeader[i].setText(StrHeaderId[i]);
			txtHeader[i].setHeight(24);
			txtHeader[i].setTextSize(12);
			txtHeader[i]
					.setBackgroundResource(R.drawable.border_color_textview);
			txtHeader[i].setTextColor(getResources().getColor(R.color.whiles));
			rowsHeader[i].addView(txtHeader[i]);
			tableHeader.addView(rowsHeader[i]);
		}
		linearHeader.addView(tableHeader);

		btnBack.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				finish();
			}
		});
	}

	private void SetOnListener() {
		btnFromDate.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				showDialog(FROM_DATE_DIALOG_ID);
			}
		});
		btnToDate.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				showDialog(TO_DATE_DIALOG_ID);
			}
		});
		btnXem.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Code = AutoCompleteStock.getText().toString().trim();
				if (!Code.equals("") && Code.length() >= 3) {
					AutoCompleteStock.setText("");
					txtStock.setText(Code);
					LoadStockInfo();
				}
			}
		});
		/*AutoCompleteStock.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> p, View v, int pos, long id) {
				Map<String, String> map = (Map<String, String>) p
						.getItemAtPosition(pos);
				String itemName = map.get("Code");
				AutoCompleteStock.setText(itemName);
				btnXem.requestFocus();
			}
		});*/
	}
	private void updateDisplayFrom() {
		txtFromDate.setText(new StringBuilder().append(pad(FromDay))
				.append("-").append(pad(FromMonth + 1)).append("-")
				.append(FromYear));
	}
	private void updateDisplayTo() {
		txtToDate.setText(new StringBuilder().append(pad(ToDay)).append("-")
				.append(pad(ToMonth + 1)).append("-").append(ToYear));
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
			case FROM_DATE_DIALOG_ID :
				return new DatePickerDialog(this, FromDateSetListener,
						FromYear, FromMonth, FromDay);

			case TO_DATE_DIALOG_ID :
				return new DatePickerDialog(this, ToDateSetListener, ToYear,
						ToMonth, ToDay);
			case DIALOG_LOADING :
				ProgressDialog dialog = new ProgressDialog(this);
				dialog.setMessage("Please wait while loading...");
				dialog.setIndeterminate(true);
				dialog.setCancelable(true);
				return dialog;
		}
		return null;
	}

	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		switch (id) {
			case FROM_DATE_DIALOG_ID :
				((DatePickerDialog) dialog).updateDate(FromYear, FromMonth,
						FromDay);
				break;
			case TO_DATE_DIALOG_ID :
				((DatePickerDialog) dialog).updateDate(ToYear, ToMonth, ToDay);
				break;
		}
	}

	private DatePickerDialog.OnDateSetListener FromDateSetListener = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			FromYear = year;
			FromMonth = monthOfYear;
			FromDay = dayOfMonth;
			updateDisplayFrom();
		}
	};
	private DatePickerDialog.OnDateSetListener ToDateSetListener = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			ToYear = year;
			ToMonth = monthOfYear;
			ToDay = dayOfMonth;
			updateDisplayTo();
		}
	};
	
	private void UpdateStockInfoUI(List<StockInfo> listStockInfo) {
		if (listStockInfo != null && listStockInfo.size() > 0) {
			linearContent.removeAllViewsInLayout();
			String text = null;
			int color = 0;
			for (StockInfo stockInfo : listStockInfo) {
				TableLayout tableContent = new TableLayout(
						HistoryActivity.this);
				TableRow[] rowContents = new TableRow[StrHeaderId.length];
				TextView[] txtContent = new TextView[StrHeaderId.length];
				for (int i = 0; i < txtContent.length; i++) {
					rowContents[i] = new TableRow(HistoryActivity.this);
					txtContent[i] = new TextView(HistoryActivity.this);
					// set text
					switch (i) {
						case 0 :
							text = stockInfo.TradeDate;
							color = R.color.whiles;
							break;
						case 1 :
							text = Common
									.FormatNumber(stockInfo.RefPrice);
							color = R.color.nochange;
							break;
						case 2 :
							text = Common
									.FormatNumber(stockInfo.CeilPrice);
							color = R.color.ceilling;
							break;
						case 3 :
							text = Common
									.FormatNumber(stockInfo.FloorPrice);
							color = R.color.floor;
							break;
						case 4 :
							text = Common
									.FormatNumber(stockInfo.PriceMatch);
							color = Common.SetColorStockInfo(
									stockInfo.PriceMatch,
									stockInfo.CeilPrice,
									stockInfo.FloorPrice,
									stockInfo.RefPrice);
							break;
						case 5 :
							text = Common
									.FormatNumber(stockInfo.Changed);
							color = Common.SetColorStockInfo(
									stockInfo.PriceMatch,
									stockInfo.CeilPrice,
									stockInfo.FloorPrice,
									stockInfo.RefPrice);
							break;
						case 6 :
							text = Common
									.FormatNumber(stockInfo.VolumeMatch);
							color = Common.SetColorStockInfo(
									stockInfo.PriceMatch,
									stockInfo.CeilPrice,
									stockInfo.FloorPrice,
									stockInfo.RefPrice);
							break;
						case 7 :
							text = Common
									.FormatNumber(stockInfo.BestPriceBuy);
							color = Common.SetColorStockInfo(
									stockInfo.BestPriceBuy,
									stockInfo.CeilPrice,
									stockInfo.FloorPrice,
									stockInfo.RefPrice);
							break;
						case 8 :
							text = Common
									.FormatNumber(stockInfo.BestVolbuy);
							color = Common.SetColorStockInfo(
									stockInfo.BestPriceBuy,
									stockInfo.CeilPrice,
									stockInfo.FloorPrice,
									stockInfo.RefPrice);
							break;
						case 9 :
							text = Common
									.FormatNumber(stockInfo.BestPriceSell);
							color = Common.SetColorStockInfo(
									stockInfo.BestPriceSell,
									stockInfo.CeilPrice,
									stockInfo.FloorPrice,
									stockInfo.RefPrice);
							break;
						case 10 :
							text = Common
									.FormatNumber(stockInfo.BestVolSell);
							color = Common.SetColorStockInfo(
									stockInfo.BestPriceSell,
									stockInfo.CeilPrice,
									stockInfo.FloorPrice,
									stockInfo.RefPrice);
							break;
						case 11 :
							text = Common
									.FormatNumber(stockInfo.TotalMatch);
							color = Common.SetColorStockInfo(
									stockInfo.PriceMatch,
									stockInfo.CeilPrice,
									stockInfo.FloorPrice,
									stockInfo.RefPrice);
							break;
					}
					txtContent[i].setText(text);
					txtContent[i].setTextColor(getResources().getColor(
							color));
					txtContent[i].setHeight(24);
					txtContent[i].setTextSize(12);
					txtContent[i].setGravity(Gravity.RIGHT);
					txtContent[i].setPadding(0, 0, 2, 0);
					LayoutParams layout = new LayoutParams(
							LayoutParams.WRAP_CONTENT,
							LayoutParams.WRAP_CONTENT);
					// layout.width = 50;
					txtContent[i].setLayoutParams(layout);

					txtContent[i]
							.setBackgroundResource(R.drawable.border_color_textview);
					rowContents[i].addView(txtContent[i], layout);
					tableContent.addView(rowContents[i]);
				}
				// add row virtual
				TableRow rowVirtual = new TableRow(HistoryActivity.this);
				tableContent.addView(rowVirtual);
				//
				linearContent.addView(tableContent);
			}
		}
	}

	
	private static String pad(int c) {
		if (c >= 10)
			return String.valueOf(c);
		else
			return "0" + String.valueOf(c);
	}
	private class CompanyInfoAsyncTask
			extends
				AsyncTask<Integer, List<CompanyInfo>, List<CompanyInfo>> {

		@Override
		protected List<CompanyInfo> doInBackground(Integer... params) {
			List<CompanyInfo> companyList = GetListCompany();
			return companyList;
		}

		@Override
		protected void onCancelled() {
			// TODO Auto-generated method stub
			super.onCancelled();
		}

		@Override
		protected void onPostExecute(List<CompanyInfo> result) {
			if (result.size() > 0) {
				List<HashMap<String, String>> listCode = new ArrayList<HashMap<String, String>>();
				HashMap<String, String> code;
				for (CompanyInfo company : result) {
					code = new HashMap<String, String>();
					code.put("Code", company.Code);
					code.put("FullName", company.FullName);
					listCode.add(code);
				}

				try {
					SimpleAdapter adapter = new SimpleAdapter(
							HistoryActivity.this, listCode,
							R.layout.two_line_list_item, new String[]{"Code",
									"FullName"}, new int[]{android.R.id.text1,
									android.R.id.text2});
					AutoCompleteStock.setAdapter(adapter);

				} catch (Exception ex) {
					Log.d(TAG, ex.toString());
				}

			}
			final Calendar c = Calendar.getInstance();
			Log.d(TAG,"End Load Company: "+c.getTime().toLocaleString());
			IsUpdateStockInfoRunning = true;
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
		}

		@Override
		protected void onProgressUpdate(List<CompanyInfo>... values) {
			super.onProgressUpdate(values);
		}
	}
	private class StockInfoAsyncTask
			extends
				AsyncTask<Void, List<StockInfo>, List<StockInfo>> {
		@Override
		protected List<StockInfo> doInBackground(Void... params) {
			List<StockInfo> listItem = null;
			try {
				listItem = GetListStockInfo();
			} catch (Exception e) {
				Log.d(TAG, e.getMessage());
			}
			return listItem;
		}

		@Override
		protected void onCancelled() {
			// TODO Auto-generated method stub
			super.onCancelled();
		}

		@Override
		protected void onPostExecute(List<StockInfo> listStockInfo) {
			UpdateStockInfoUI(listStockInfo);
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
		}

		@Override
		protected void onProgressUpdate(List<StockInfo>... listStockInfo) {
			
		}

	}
	private List<CompanyInfo> GetListCompany() {
		List<CompanyInfo> companyList = new ArrayList<CompanyInfo>();
		Cursor cur = dbData.Select("select * from "
				+ CompanyInfo.TABLE_NAME);
		if (cur.getCount() > 0) {
			while (cur.moveToNext()) {
				CompanyInfo comp = new CompanyInfo();
				comp.Code = cur.getString(cur.getColumnIndex(CompanyInfo.CODE));
				comp.FullName = cur.getString(cur.getColumnIndex(CompanyInfo.FULLNAME));
				companyList.add(comp);
			}
		}
		cur.close();
		dbData.close();
		return companyList;
	}
	private List<StockInfo> GetListStockInfo() {
		List<StockInfo> listStockInfo = null;
		Log.d(TAG, "Get Data From Database");
		StringBuilder whereArg = new StringBuilder();
		whereArg.append(StockInfo.SYMBOL);
		whereArg.append("='");
		whereArg.append(Code);
		whereArg.append("'");

		whereArg.append(" and ");
		whereArg.append(StockInfo.TRADE_DATE);
		whereArg.append(">='");
		whereArg.append(FromYear + "-" + pad(FromMonth + 1) + "-"
				+ pad(FromDay));
		whereArg.append("'");

		whereArg.append(" and ");
		whereArg.append(StockInfo.TRADE_DATE);
		whereArg.append("<='");
		whereArg.append(ToYear + "-" + pad(ToMonth + 1) + "-" + pad(ToDay));
		whereArg.append("'");

		String sql = String.format("select * from %s where %s ",
				StockInfo.TABLE_NAME, whereArg);
		Log.d(TAG, sql);
		Cursor listStockCursor = dbData.Select(sql);
		Log.d(TAG, listStockCursor.getCount() + "----");
		if (listStockCursor.getCount() > 0) {
			listStockInfo = new ArrayList<StockInfo>();
			while (listStockCursor.moveToNext()) {
				StockInfo stock = new StockInfo();
				stock.Symbol = listStockCursor.getString(listStockCursor
						.getColumnIndex(StockInfo.SYMBOL));
				stock.RefPrice = listStockCursor.getFloat(listStockCursor
						.getColumnIndex(StockInfo.REF_PRICE));
				stock.CeilPrice = listStockCursor.getFloat(listStockCursor
						.getColumnIndex(StockInfo.CEIL_PRICE));
				stock.FloorPrice = listStockCursor.getFloat(listStockCursor
						.getColumnIndex(StockInfo.FLOOR_PRICE));
				stock.PriceMatch = listStockCursor.getFloat(listStockCursor
						.getColumnIndex(StockInfo.PRICE_MATCH));
				stock.Changed = listStockCursor.getFloat(listStockCursor
						.getColumnIndex(StockInfo.CHANGED));
				stock.PerChanged = listStockCursor.getFloat(listStockCursor
						.getColumnIndex(StockInfo.PER_CHANGED));
				stock.VolumeMatch = listStockCursor.getFloat(listStockCursor
						.getColumnIndex(StockInfo.VOLUME_MATCH));
				stock.TotalMatch = listStockCursor.getFloat(listStockCursor
						.getColumnIndex(StockInfo.TOTAL_MATCH));

				stock.BestPriceBuy = listStockCursor.getFloat(listStockCursor
						.getColumnIndex(StockInfo.BEST_PRICE_BUY));
				stock.BestVolbuy = listStockCursor.getFloat(listStockCursor
						.getColumnIndex(StockInfo.BEST_VOL_BUY));
				stock.BestPriceSell = listStockCursor.getFloat(listStockCursor
						.getColumnIndex(StockInfo.BEST_PRICE_SELL));
				stock.BestVolSell = listStockCursor.getFloat(listStockCursor
						.getColumnIndex(StockInfo.BEST_VOL_SELL));
				stock.TradeDate = listStockCursor.getString(listStockCursor
						.getColumnIndex(StockInfo.TRADE_DATE));
				listStockInfo.add(stock);
			}
		}
		listStockCursor.close();
		dbData.close();
		return listStockInfo;

	}
	private void LoadCompanyInfo() {
		CancelLoadCompanyInfo();
		companyInfoAsyncTask = new CompanyInfoAsyncTask();
		companyInfoAsyncTask.execute(0);
	}

	private void CancelLoadCompanyInfo() {
		if (companyInfoAsyncTask != null) {
			companyInfoAsyncTask.cancel(true);
			companyInfoAsyncTask = null;
		}
	}
	private void LoadStockInfo() {
		CancelLoadStockInfo();
		stockInfoAsyncTask = new StockInfoAsyncTask();
		stockInfoAsyncTask.execute();
	}
	private void CancelLoadStockInfo() {
		if (stockInfoAsyncTask != null) {
			stockInfoAsyncTask.cancel(true);
			stockInfoAsyncTask = null;
		}
	}

}
